Ext.define('CA.catalog.FilterTree', {
    extend: 'Ext.tree.Panel',
    xtype: 'CA.catalog.FilterTree',

    viewConfig: {
        loadMask: false
    },

    initComponent: function(){
        var config = {
            rootVisible: false,
            clearOnLoad: true,
            root: { expanded: true },
            store: this.buildStore()
        };

        Ext.apply(this, config);

        this.on('checkchange', this.onCheckChange, this);

        this.callParent();
    },

    onBeforeLoad: function(store, operation){
        var params = {
            extraParams: {}
        };

        if(operation.action == 'read'){
            params.extraParams.checked = !!operation.node.data.checked;
        }

        Ext.apply(store.proxy, params);
    },

    onCheckChange: function(node, checked){
        node.cascadeBy(function(){
            this.set('checked', checked);
        });

        var checkParents = function(pNode){
            var hasChecked = false,
                parent = pNode.parentNode;

            if(parent){
                Ext.each(node.parentNode.childNodes, function(n){
                    if(n.get('checked') === true){
                        hasChecked = true;
                        return false;
                    }
                });

                parent.set('checked', hasChecked);

                checkParents(parent);
            }
        };

        checkParents(node);
    },

    buildStore: function(){
        var store = Ext.create('Ext.data.TreeStore', {
            autoLoad: false,
            nodeParam: 'node',
            proxy: {
                paramOrder: ['node', 'checked'],
                type: 'direct',
                api : {
                    read: TreeTest.read,
                    create: TreeTest.create
                },
                reader: {
                    type:'json',
                    root: 'data'
                }
            }
        });

        store.on('beforeload', this.onBeforeLoad, this);

        return store;
    }
});